package com.cneiu.ppms.web.service;

import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import com.cneiu.ppms.web.base.BaseService;
import com.cneiu.ppms.web.model.RoleAuthModel;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
/**
 * 系统角色权限业务
 * @author jiangli
 * @date 2013-04-21
 */
public class RoleAuthService extends BaseService{
	
	/**
	 * 分页列出角色权限
	 * @param page
	 * @param limit
	 * @param search
	 * @return
	 */
	public static Page<RoleAuthModel> list(Map<String,String> params){
		JSONObject search = JSONObject.fromObject(params.get("search"));
		int limit = 0;
		int page = 1;
		try{
			limit = params.get("limit")==null?10:Integer.parseInt(params.get("limit").toString());
			page = params.get("page")==null?1:Integer.parseInt(params.get("page").toString());
		}catch (Exception e){
			limit = 10;
			page = 1;
		}
		StringBuffer where = new StringBuffer();;
		try{
			if (search.get("auth_no") != null){
				where.append(" AND AUTH_NO=" + search.get("auth_no"));
			}
			if (search.get("auth_role_no") != null){
				where.append(" AND AUTH_ROLE_NO=" + search.get("auth_role_no"));
			}
		}catch (Exception e){
		}
		Page<RoleAuthModel> actions = null;
		
		String select_sql = "SELECT * ";
		String query_sql = "FROM SA_ROLE_AUTH WHERE 1=1 " + where;
		try{
			actions = RoleAuthModel.dao.paginate(page, limit, select_sql, query_sql);
		}catch (Exception e){
			setError(e.getMessage());
		}
		return actions;
	}

	/**
	 * 添加角色权限功能
	 * @param params
	 * @return
	 */
	public static boolean isAdd(Map<String,String> params){
		String SQL = "insert into SA_ROLE_AUTH(AUTH_ROLE_NO,AUTH_NO) values(?,?)";
		int isupadded = Db.update(SQL, params.get("auth_role_no"),params.get("auth_no"));
		if(isupadded==1){
			return true;
		}
		return setError("保存角色权限失败！");
	}

	/**
	 * 根据用户ID查询角色相关的权限
	 * @param params
	 * @return
	 */
	public static List<RoleAuthModel> get(Map<String,String> params){
		String no = params.get("auth_role_no")==null?"":params.get("auth_role_no").toString();
		List<RoleAuthModel> pp = RoleAuthModel.dao.find("SELECT * FROM SA_ROLE_AUTH WHERE AUTH_ROLE_NO=?", no);
		return pp;
	}

	/**
	 * 删除角色权限（根据角色和权限ID删除）
	 * @param params
	 * @return
	 */
	public static boolean isDelete(Map<String,String> params){
		String SQL = "delete from SA_ROLE_AUTH where AUTH_ROLE_NO=? and AUTH_NO=?";
		int deleted = Db.update(SQL, params.get("auth_role_no"),params.get("auth_no"));
		if (deleted==1){
			return true;
		}
		return setError("您访问的角色权限不存在！");
	}
}
